package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.intercepter.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoTo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    @Qualifier("threadPoolExecutor")
    private Executor executor;

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> boundHashOps = getCartItemsOps();
        String cartItemStr = (String) boundHashOps.get(skuId.toString());
        return JSON.parseObject(cartItemStr,CartItem.class);
    }

    @Override
    public void addToCart(Long skuId, Long num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartItemsOps = getCartItemsOps();
        String cartItemStr = (String) cartItemsOps.get(skuId.toString());
        if (cartItemStr!=null){
            CartItem cartItem = JSON.parseObject(cartItemStr, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num.intValue());
            cartItemsOps.put(skuId.toString(),JSON.toJSONString(cartItem));
        }else {
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoTo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoTo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num.intValue());
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setSkuId(skuId);
                cartItem.setTitle(skuInfo.getSkuTitle());
            }, executor);
            CompletableFuture<Void> skuAttFuture = CompletableFuture.runAsync(() -> {
                List<String> skuAttrs = productFeignService.getSaleAttrsBySkuId(skuId);
                cartItem.setSkuAttr(skuAttrs);
            }, executor);

            CompletableFuture.allOf(skuInfoFuture,skuAttFuture).get();
            cartItemsOps.put(skuId.toString(),JSON.toJSONString(cartItem));
        }
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        String cartKey = "";
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            BoundHashOperations<String, Object, Object> tempCartOps = redisTemplate.boundHashOps(CartConstant.CART_REDIS_PREFIX + userInfoTo.getUserKey());
            BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(CartConstant.CART_REDIS_PREFIX + userInfoTo.getUserId().toString());
            List<Object> tempCartItems = tempCartOps.values();
            if (tempCartItems!=null && tempCartItems.size()>0) {
                for (Object tempCartItem : tempCartItems) {
                    String str = (String) tempCartItem;
                    CartItem cartItem = JSON.parseObject(str, CartItem.class);
                    Boolean hasKey = cartOps.hasKey(cartItem.getSkuId().toString());
                    if (hasKey){
                        String cartItemInCartStr = (String) cartOps.get(cartItem.getSkuId().toString());
                        CartItem cartItemInCart = JSON.parseObject(cartItemInCartStr, CartItem.class);
                        cartItem.setCount(cartItemInCart.getCount()+cartItem.getCount());
                        cartOps.put(cartItem.getSkuId().toString(),JSON.toJSONString(cartItem));
                    }else {
                        cartOps.put(cartItem.getSkuId().toString(),str);
                    }
                }
            }
            redisTemplate.delete(CartConstant.CART_REDIS_PREFIX + userInfoTo.getUserKey());
            cartKey = userInfoTo.getUserId().toString();
        }else {
            cartKey = userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(CartConstant.CART_REDIS_PREFIX + cartKey);
        List<Object> cartItems = cartOps.values();
        if (cartItems!=null&& cartItems.size()>0 ){
            List<CartItem> collect = cartItems.stream().map(item -> JSON.parseObject((String) item, CartItem.class)).collect(Collectors.toList());
            cart.setItems(collect);

        }
        cart.setReduce(new BigDecimal("0"));
        return cart;
    }

    @Override
    public void checkChange(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartItemsOps = getCartItemsOps();
        String  cartItemStr = (String) cartItemsOps.get(skuId.toString());
        if (cartItemStr!=null){
            CartItem cartItem = JSON.parseObject(cartItemStr,CartItem.class);
            cartItem.setCheck(check == 1);
            cartItemsOps.put(skuId.toString(),JSON.toJSONString(cartItem));
        }
    }

    @Override
    public void countChange(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartItemsOps = getCartItemsOps();
        String  cartItemStr = (String) cartItemsOps.get(skuId.toString());
        if (cartItemStr!=null){
            CartItem cartItem = JSON.parseObject(cartItemStr,CartItem.class);
            cartItem.setCount(num);
            cartItemsOps.put(skuId.toString(),JSON.toJSONString(cartItem));
        }
    }

    @Override
    public void deleteItem(Long skuId) {
        this.getCartItemsOps().delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(CartConstant.CART_REDIS_PREFIX+userInfoTo.getUserId().toString());
            List<Object> values = boundHashOps.values();
            if(values!=null&& values.size()>0){
                List<CartItem> collect = values.stream().map(i-> JSON.parseObject((String) i,CartItem.class))
                        .filter(item ->  item.getCheck())
                        .map(item->{
                            BigDecimal price = productFeignService.getPrice(item.getSkuId());
                            item.setPrice(price);
                            return item;
                        })
                        .collect(Collectors.toList());
                return collect;
            }
            return null;
        }else {
            return null;
        }
    }

    private BoundHashOperations<String, Object, Object> getCartItemsOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        BoundHashOperations<String, Object, Object> boundHashOps;
        if (userInfoTo.getUserId()!=null){
            boundHashOps = redisTemplate.boundHashOps(CartConstant.CART_REDIS_PREFIX+userInfoTo.getUserId().toString());
        }else {
            boundHashOps = redisTemplate.boundHashOps(CartConstant.CART_REDIS_PREFIX+userInfoTo.getUserKey());
        }
        return boundHashOps;
    }
}
